package com.hd.trans.utils;

import android.content.Context;
import android.text.TextUtils;

import com.hd.trans.common.interf.WebTransCallback;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class WebTransUtil {

    private static boolean isHttpString(String urlString){
        return urlString.startsWith("http");
    }

    public static void parseTextByUrl(String urlString, WebTransCallback callback){
        if(!isHttpString(urlString)){
            callback.parseFailed("请输入正确的网址");
            return;
        }


        String spanned = httpGet(urlString,true, callback);
        if(TextUtils.isEmpty(spanned))return;

        String spannedString  =  HtmlCompat.fromHtml(getHtml2Text(spanned)).toString();
        //String spannedString  =  getHtml2Text(spanned);
        if(spannedString.length()>10000){//截取前面10000个字符
            spannedString = spannedString.substring(10000);
        }
        callback.parseTextCallback(spannedString.replace("\n\n","\n"));
    }

    private static void onFailed(WebTransCallback callback){
        callback.parseFailed("查找网址内容为空");
    }

    private static String getHtml2Text(CharSequence htmlStr){
        String textStr = "";
        try {
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }
            String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式

            Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            Matcher m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); //过滤script标签

            Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            Matcher m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); //过滤style标签

//            Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
//            Matcher m_html = p_html.matcher(htmlStr);
//            htmlStr = m_html.replaceAll(""); //过滤html标签

            textStr = htmlStr.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return removeKong(textStr.replace('\t', '\n')); //返回文本字符串
    }

    private static String removeKong(String textStr){
        String w = "";
        //替换多个空字符串
        Pattern p = Pattern.compile("\\s+");
        Matcher m = p.matcher(textStr);
        w = m.replaceAll(" ");

        //除去html的常用标签
        Pattern p4 = Pattern.compile("(&nbsp;)|(&quot;)|(&raquo;)|(&bull;)|(&lt;)|(&gt;)|(&ldquo;)");
        Matcher m4 = p4.matcher(w);
        w = m4.replaceAll("");

        //替换；和。号为换行
        Pattern p2 = Pattern.compile(";");
        Matcher m2 = p2.matcher(w);
        w = m2.replaceAll(";\n");

        Pattern p3 = Pattern.compile("。");
        Matcher m3= p3.matcher(w);
        w = m3.replaceAll("。\n");

        Pattern p5 = Pattern.compile(">");
        Matcher m5 = p5.matcher(w);
        w = m5.replaceAll(">\n");

        return w;
    }

    /**
     * 信任所有服务器，无需验证证书
     */
    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
        } };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String httpGet(String httpUrl,boolean recursion, WebTransCallback callback) {
        BufferedReader input = null;
        StringBuilder sb = null;
        URL url = null;
        HttpURLConnection con = null;
        try {
            url = new URL(httpUrl);
            try {
                // trust all hosts

                if (url.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https= (HttpsURLConnection) url.openConnection();
                    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

                        @Override
                        public boolean verify(String hostname, SSLSession sslsession) {

                            /*if("host".equals(hostname)){
                                return true;
                            } else {
                                return false;
                            }*/

                            return true;//信任所有域名
                        }});
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                    con = https;
                } else {
                    con = (HttpURLConnection)url.openConnection();
                }

                if(con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    input = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    sb = new StringBuilder();
                    String line;
                    while ((line = input.readLine()) != null) {
                        sb.append(line);
                    }
                }else {
                    if(recursion){
                        con.disconnect();

                        if(httpUrl.startsWith("https")){
                            httpUrl = httpUrl.replace("https","http");
                        }else {
                            httpUrl = httpUrl.replace("http","https");
                        }
                        return httpGet(httpUrl,false,callback);
                    }else {
                        onFailed(callback);
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
                onFailed(callback);
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            onFailed(callback);
        } finally {
            // close buffered
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // disconnecting releases the resources held by a connection so they may be closed or reused
            if (con != null) {
                con.disconnect();
            }
        }

        return sb == null ? null : sb.toString();
    }
    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {

        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    /**
     * 获取Https的证书
     * @param context Activity（fragment）的上下文
     * @return SSL的上下文对象
     */
    private static SSLContext getSSLContext(Context context) {
        SSLContext s_sSLContext = null;
        if (null != s_sSLContext) {
            return s_sSLContext;
        }

        CertificateFactory certificateFactory = null;

        InputStream inputStream = null;
        KeyStore keystore = null;
        String tmfAlgorithm = null;
        TrustManagerFactory trustManagerFactory = null;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509");

            inputStream = context.getAssets().open("user.crt");//这里导入SSL证书文件
            //            inputStream = context.getAssets().open("51p2b_server_bs.pem");//这里导入SSL证书文件

            Certificate ca = certificateFactory.generateCertificate(inputStream);

            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setCertificateEntry("ca", ca);

            tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
            trustManagerFactory.init(keystore);

            // Create an SSLContext that uses our TrustManager
            s_sSLContext = SSLContext.getInstance("TLS");
            s_sSLContext.init(null, trustManagerFactory.getTrustManagers(), null);
            return s_sSLContext;
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String httpGet(Context context,String httpUrl) {
        BufferedReader input = null;
        StringBuilder sb = null;
        URL url = null;
        HttpURLConnection con = null;
        try {
            url = new URL(httpUrl);
            try {
                SSLContext sslContext = getSSLContext(context);
                HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
                HttpsURLConnection https= (HttpsURLConnection) url.openConnection();
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

                    @Override
                    public boolean verify(String hostname, SSLSession sslsession) {

                        if("host".equals(hostname)){//判断域名是否和证书域名相等
                            return true;
                        } else {
                            return false;
                        }
                    }});
                if (url.getProtocol().toLowerCase().equals("https")) {//判断是http还是https
                    //https.setHostnameVerifier(DO_NOT_VERIFY);
                    con = https;
                } else {
                    con = (HttpURLConnection)url.openConnection();
                }
                input = new BufferedReader(new InputStreamReader(con.getInputStream()));
                sb = new StringBuilder();
                String s;
                while ((s = input.readLine()) != null) {
                    sb.append(s).append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } finally {
            // close buffered
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // disconnecting releases the resources held by a connection so they may be closed or reused
            if (con != null) {
                con.disconnect();
            }
        }

        return sb == null ? null : sb.toString();
    }
}
